<?php
// 设置允许的来源，这里假设允许来自 http://1.13.198.191:8081 的请求
// header("Access-Control-Allow-Origin: http://1.13.198.191:8081");
// header("Access-Control-Allow-Origin: http://localhost:9528");
header("Access-Control-Allow-Origin: http://localhost:9528");
// 允许携带凭证
header("Access-Control-Allow-Credentials: true");
// 允许的HTTP方法
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// 允许的请求头
header("Access-Control-Allow-Headers: Content-Type");

// 处理预检请求（OPTIONS）
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once "./conn.php";
require_once "./usersession.php";
require_once "./page/Page.php";

// 获取前端传来的 JSON 数据
$input = file_get_contents("php://input");
$data = json_decode($input, true);

// 获取参数
$page = isset($data['page']) ? $data['page'] : 1;
$pagenum = isset($data['pagenum']) ? $data['pagenum'] : 50;
$offset = ($page - 1) * $pagenum;

$user_status = isset($data['user_status']) ? $data['user_status'] : '';
$user_gold_coin1 = isset($data['user_gold_coin1']) ? $data['user_gold_coin1'] : '';
$user_gold_coin2 = isset($data['user_gold_coin2']) ? $data['user_gold_coin2'] : '';
$user_activity1 = isset($data['user_activity1']) ? $data['user_activity1'] : '';
$user_activity2 = isset($data['user_activity2']) ? $data['user_activity2'] : '';
$user_device_name = isset($data['user_device_name']) ? $data['user_device_name'] : '';
$user_account = isset($data['user_account']) ? $data['user_account'] : '';
$user_zone_name = isset($data['user_zone_name']) ? $data['user_zone_name'] : '';
$user_sect = isset($data['user_sect']) ? $data['user_sect'] : '';
$user_level1 = isset($data['user_level1']) ? $data['user_level1'] : '';
$user_level2 = isset($data['user_level2']) ? $data['user_level2'] : '';
$start_time = isset($data['start_time']) ? $data['start_time'] : '2021-06-01T00:00:00';
$start_time = str_replace("T", " ", $start_time);
$end_time = isset($data['end_time']) ? $data['end_time'] : date('Y-m-d');
$end_time = str_replace("T", " ", $end_time);
$keywords = isset($data['keywords']) ? $data['keywords'] : '';
$notgl = isset($data['notgl']) ? $data['notgl'] : '';
$orderByCoinr = isset($data['orderByCoinr']) ? $data['orderByCoinr'] : '';
$exportType = isset($data['exportType']) ? $data['exportType'] : ''; // 新增导出类型参数

// 计算总记录数
$countSql = "SELECT COUNT(*) as total FROM roles WHERE 1=1";
$countWhere = "";

if ($user_status != '' && $user_status) {
    if ($user_status != '全部') {
        if ($user_status == '已完成+运行中') {
            $countWhere .= " and user_status != '隔离'";
        } else {
            $countWhere .= " and user_status = '" . $user_status . "'";
        }
    }
}

if ($user_device_name != '') {
    $countWhere .= " and user_device_name = '" . $user_device_name . "'";
}
if ($user_account != '') {
    $countWhere .= " and user_account like '%" . $user_account . "%'";
}
if ($user_zone_name != '') {
    $countWhere .= " and user_zone_name like '%" . $user_zone_name . "%'";
}
if ($user_sect != '') {
    $countWhere .= " and user_sect like '%" . $user_sect . "%'";
}

if ($user_level2 != '') {
    $countWhere .= " and user_level " . $user_level1 . $user_level2;
}

if ($user_activity2 != '') {
    $countWhere .= " and user_activity " . $user_activity1 . $user_activity2;
}
if ($user_gold_coin2 != '') {
    $countWhere .= " and user_gold_coin " . $user_gold_coin1 . $user_gold_coin2;
}

if ($start_time && $end_time) {
    $countWhere .= " and update_time between '{$start_time}' and '{$end_time}'";
}

if ($notgl == 'notgl') {
    $countWhere .= " and user_status != '隔离'";
}

if ($keywords && $keywords !== '') {
    $countSql = "SELECT COUNT(*) as total FROM roles
            WHERE (user_device_name LIKE CONCAT('%','$keywords','%')
            OR user_account LIKE CONCAT('%','$keywords','%')
            OR user_zone_name LIKE CONCAT('%','$keywords','%')
            OR user_role LIKE CONCAT('%','$keywords','%')
            OR user_level LIKE CONCAT('%','$keywords','%')
            OR user_sect LIKE CONCAT('%','$keywords','%')
            OR user_gold_coin LIKE CONCAT('%','$keywords','%')
            OR user_silver_coin LIKE CONCAT('%','$keywords','%')
            OR user_activity LIKE CONCAT('%','$keywords','%')
            OR user_status LIKE CONCAT('%','$keywords','%')) 
            AND user_zhongkong_name = '$username'";
} else {
    $countSql .= " and user_zhongkong_name = '" . $username . "'";
}

$countStmt = $conn->prepare($countSql);
if (!$countStmt) {
    die('准备语句失败: ' . $conn->error);
}
$countStmt->execute();
$countResult = $countStmt->get_result();
$countRow = $countResult->fetch_assoc();
$totalRecords = $countRow['total'];

// 查询
$sql = "SELECT * FROM roles WHERE 1=1"; // 初始化where

if ($user_status != '' && $user_status) {
    if ($user_status != '全部') {
        if ($user_status == '已完成+运行中') {
            $sql .= " and user_status != '隔离'";
        } else {
            $sql .= " and user_status = '" . $user_status . "'";
        }
    }
}

if ($user_device_name != '') {
    $sql .= " and user_device_name = '" . $user_device_name . "'";
}
if ($user_account != '') {
    $sql .= " and user_account like '%" . $user_account . "%'";
}
if ($user_zone_name != '') {
    $sql .= " and user_zone_name like '%" . $user_zone_name . "%'";
}
if ($user_sect != '') {
    $sql .= " and user_sect like '%" . $user_sect . "%'";
}

if ($user_level2 != '') {
    $sql .= " and user_level " . $user_level1 . $user_level2;
}

if ($user_activity2 != '') {
    $sql .= " and user_activity " . $user_activity1 . $user_activity2;
}
if ($user_gold_coin2 != '') {
    $sql .= " and user_gold_coin " . $user_gold_coin1 . $user_gold_coin2;
}

if ($start_time && $end_time) {
    $sql .= " and update_time between '{$start_time}' and '{$end_time}'";
}

if ($notgl == 'notgl') {
    $sql .= " and user_status != '隔离'";
}

if ($keywords && $keywords !== '') {
    $sql = "SELECT * FROM roles
            WHERE (user_device_name LIKE CONCAT('%','$keywords','%')
            OR user_account LIKE CONCAT('%','$keywords','%')
            OR user_zone_name LIKE CONCAT('%','$keywords','%')
            OR user_role LIKE CONCAT('%','$keywords','%')
            OR user_level LIKE CONCAT('%','$keywords','%')
            OR user_sect LIKE CONCAT('%','$keywords','%')
            OR user_gold_coin LIKE CONCAT('%','$keywords','%')
            OR user_silver_coin LIKE CONCAT('%','$keywords','%')
            OR user_activity LIKE CONCAT('%','$keywords','%')
            OR user_status LIKE CONCAT('%','$keywords','%')) 
            AND user_zhongkong_name = '$username'";
} else {
    $sql .= " and user_zhongkong_name = '" . $username . "'";
}
// if ($orderByCoinr == 'orderByCoinr') {
//     $sql .= " order by user_gold_coin*1 desc";
// } else {
//     $sql .= " order by update_time desc";
// }

// 根据导出类型处理查询结果
if ($exportType == 'all') {
    // 处理排序
    if ($orderByCoinr == 'orderByCoinr') {
        $sql .= " order by user_gold_coin*1 desc";
    } else {
        $sql .= " order by update_time desc";
    }
    // 全部导出
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        die('准备语句失败: ' . $conn->error);
    }
} elseif ($exportType == 'current') {
    // 处理排序
    if ($orderByCoinr == 'orderByCoinr') {
        $sql .= " order by user_gold_coin*1 desc";
    } else {
        $sql .= " order by update_time desc";
    }
    // 导出此页
    $sql .= " limit ?,?";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        die('准备语句失败: ' . $conn->error);
    }
    $stmt->bind_param("ii", $offset, $pagenum);
} elseif ($exportType == 'selected') {
    // 导出选中
    $selectedIds = isset($data['selectedIds']) ? $data['selectedIds'] : '';
    if (!empty($selectedIds)) {
        $sql .= " and id in (" . $selectedIds . ")";
        // 处理排序
        if ($orderByCoinr == 'orderByCoinr') {
            $sql .= " order by user_gold_coin*1 desc";
        } else {
            $sql .= " order by update_time desc";
        }
        // echo $sql;
        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            die('准备语句失败: ' . $conn->error);
        }
    } else {
        $stmt = $conn->prepare("SELECT * FROM roles WHERE 1=0"); // 返回空结果
        if (!$stmt) {
            die('准备语句失败: ' . $conn->error);
        }
    }
} else {
    // 处理排序
    if ($orderByCoinr == 'orderByCoinr') {
        $sql .= " order by user_gold_coin*1 desc";
    } else {
        $sql .= " order by update_time desc";
    }
    // 默认查询
    $sql .= " limit ?,?";
    // echo $sql;
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        die('准备语句失败: ' . $conn->error);
    }
    $stmt->bind_param("ii", $offset, $pagenum);
}

$result = [];

if ($stmt->execute()) {
    if ($rs = $stmt->get_result()) {
        $totalGoldCoin = 0; // 总金币
        $pageGoldCoin = 0; // 本页金币

        while ($row = $rs->fetch_assoc()) {
            $goldCoin = is_numeric($row['user_gold_coin']) ? floatval($row['user_gold_coin']) : 0;
            $userLevel = is_numeric($row['user_level']) ? intval($row['user_level']) : 0; // 转换 user_level 为整数
            $userActivity = is_numeric($row['user_activity']) ? intval($row['user_activity']) : 0; // 转换 user_level 为整数
            $result[] = [
                'id' => $row['id'],
                'user_device_name' => $row['user_device_name'],
                'user_account' => $row['user_account'],
                'user_password' => $row['user_password'],
                'user_zone_name' => $row['user_zone_name'],
                'user_name' => $row['user_name'],
                'user_role' => $row['user_role'],
                'user_level' => $userLevel,
                'user_id' => $row['user_id'],
                'user_sect' => $row['user_sect'],
                'user_gold_coin' => $goldCoin,
                'user_silver_coin' => $row['user_silver_coin'],
                'user_activity' => $userActivity,
                'user_status' => $row['user_status'],
                'user_run_time' => $row['user_run_time'],
                'user_last_time' => $row['update_time'],
                'comment' => $row['comment'],
                'user_gem_hammer' => intval($row['user_gem_hammer']),
                'frozen_gold_coin' => floatval($row['frozen_gold_coin']),
                'gold_coin_growth' => floatval($row['gold_coin_growth']),
            ];
            $pageGoldCoin += $goldCoin; // 累加本页金币
        }

        // 确保总金币是从数据库中获取的，而不是从当前页累加的
        $totalGoldCoinSql = "SELECT SUM(user_gold_coin) as total_gold_coin FROM roles WHERE user_zhongkong_name = '" . $username . "'";
        $totalGoldCoinStmt = $conn->prepare($totalGoldCoinSql);
        if (!$totalGoldCoinStmt) {
            die('准备语句失败: ' . $conn->error);
        }
        $totalGoldCoinStmt->execute();
        $totalGoldCoinResult = $totalGoldCoinStmt->get_result();
        $totalGoldCoinRow = $totalGoldCoinResult->fetch_assoc();
        $totalGoldCoin = is_numeric($totalGoldCoinRow['total_gold_coin']) ? floatval($totalGoldCoinRow['total_gold_coin']) : 0;
    }
}

// 使用 Page 类计算分页信息
$pageObj = new Page($totalRecords, 10, $page, $pagenum);
$pageInfo = [
    'TotalRecords' => $totalRecords,
    'CurrentPage' => $page,
    'PageSize' => $pagenum,
    'TotalPages' => $pageObj->getTotalPages()
];

// 生成 CSV 数据
if ($exportType) {
    $csvData = [];
    $columns = ['设备名称', '账号', '密码', '区服', '用户名', '角色', '等级', 'ID', '门派', '金币', '银币', '活跃度', '状态', '运行时间', '最后更新时间', '更新时间', '备注', '宝石锤', '冻结金币', '金币涨幅'];

    // 添加列名
    $csvData[] = $columns;

    foreach ($result as $item) {
        $csvData[] = [
            $item['user_device_name'],
            $item['user_account'],
            $item['user_password'],
            $item['user_zone_name'],
            $item['user_name'],
            $item['user_role'],
            $item['user_level'],
            $item['user_id'],
            $item['user_sect'],
            $item['user_gold_coin'],
            $item['user_silver_coin'],
            $item['user_activity'],
            $item['user_status'],
            $item['user_run_time'],
            $item['user_last_time'],
            $item['comment'],
            $item['user_gem_hammer'],
            $item['frozen_gold_coin'],
            $item['gold_coin_growth']
        ];
    }

    // 将数据转换为 CSV 格式
    $csvContent = '';
    foreach ($csvData as $row) {
        $csvContent .= implode(',', $row) . "\n";
    }

    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="export.csv"');
    echo $csvContent;
    exit;
}

header('Content-Type: application/json');
echo json_encode([
    'Code' => 200,
    'Msg' => '查询成功',
    'Ret' => "True",
    'Data' => $result,
    'PageInfo' => $pageInfo,
    'TotalGoldCoin' => $totalGoldCoin,
    'PageGoldCoin' => $pageGoldCoin,
    'Total' => $totalRecords
], JSON_UNESCAPED_UNICODE);
